package website.seamonster.ethegg.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import website.seamonster.ethegg.dataobject.Egg;
import website.seamonster.ethegg.dataobject.EggCounter;
import website.seamonster.ethegg.repository.EggCounterRepository;
import website.seamonster.ethegg.repository.EggRepository;
import website.seamonster.ethegg.utils.BatchNumUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;

/**
 * 为"未分配"的蛋分配次序、批次、价格
 * Created by 罗海量
 * 2018-07-20 01:42
 */
@lombok.extern.slf4j.Slf4j
@Service
public class AssignEggService {
    @Autowired
    private EggCounterRepository counterRepository;

    @Autowired
    private EggRepository eggRepository;

    private final BigDecimal alphaPrice = new BigDecimal("0.9");

    @Transactional
    public void assign(int recordCnt){
        //TODO 似乎需要做成串行化
        //查询一批（最大数目不超过recordCnt）未分配的蛋
        List<Egg> eggList = this.findEggsToAssign(recordCnt);
        //获取当前计数器
        List<EggCounter> counters = counterRepository.findAll();
        long cnt = counters.get(0).getCnt();
        long updateRecordCnt = 0;
        //依次为蛋分配序号
        for (Egg e : eggList){
            long seq = ++cnt;
            int batchNum = BatchNumUtils.getBatchNumFromCount(seq);
            BigDecimal price = alphaPrice.pow(batchNum);
            e.setSeq(seq);
            e.setBatchNum(batchNum);
            e.setPrice(price);
            //TODO 对比蛋的批次与当前出售批次，决定是待售中还是出售中
            eggRepository.save(e);
            updateRecordCnt++;
        }
        //蛋计数器加特定的值
        counterRepository.add(updateRecordCnt);
    }

    private List<Egg> findEggsToAssign(int recordCnt){
        PageRequest pageRequest = new PageRequest(0, recordCnt);
        Page<Egg> eggPage = eggRepository.findBySeqAndBatchNumOrderById((long) 0, 0, pageRequest);
        return eggPage.getContent();
    }




}
